import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_xupdate/flutter_xupdate.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '打包，升级，发布',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _message = '';
  String _customJson = '';
  final String _updateUrl =
      'https://gitee.com/xuexiangjys/XUpdate/raw/master/jsonapi/update_test.json';

  @override
  void initState() {
    super.initState();
    initXUpdate();
    loadJsonFromAsset();
  }

  void initXUpdate() {
    if (Platform.isAndroid) {
      FlutterXUpdate.init(

              ///是否输出日志
              debug: true,

              ///是否使用post请求
              isPost: false,

              ///post请求是否是上传json
              isPostJson: false,

              ///是否开启自动模式
              isWifiOnly: false,

              ///是否开启自动模式
              isAutoMode: false,

              ///需要设置的公共参数
              supportSilentInstall: false,

              ///在下载过程中，如果点击了取消的话，是否弹出切换下载方式的重试提示弹窗
              enableRetry: false)
          .then((value) {
        updateMessage('初始化成功：$value');
      }).catchError((errer) => print(errer));

      FlutterXUpdate.setErrorHandler(
          onUpdateError: (Map<String, dynamic>? message) async {
        print(message);
        //下载失败
        if (message!['code'] == 4000) {
          FlutterXUpdate.showRetryUpdateTipDialog(
              retryContent: 'Gitee下载出错，是否尝试别的下载方法',
              retryUrl: 'https://www.baidu.cn');
        }
        setState(() {
          _message = '$message';
        });
      });
    } else {
      updateMessage('ios暂不支持XUpdata更新');
    }
  }

  //加载本地版本json文件。
  Future<void> loadJsonFromAsset() async {
    _customJson = await rootBundle.loadString('assets/update_custom.json');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('更新第二版'),
      ),
      body: Center(
        child: Column(
          children: [
            TextButton(onPressed: checkUpdateDefault, child: Text('默认更新'))
          ],
        ),
      ),
    );
  }

  void updateMessage(String message) {
    setState(() {
      _message = message;
    });
  }

  void checkUpdateDefault() {
    FlutterXUpdate.checkUpdate(url: _updateUrl);
  }
}
